package org.shijiagen.user.controller;

import lombok.RequiredArgsConstructor;
import org.shijiagen.param.UserCheckParam;
import org.shijiagen.param.UserLoginParam;
import org.shijiagen.pojo.User;
import org.shijiagen.user.service.UserService;
import org.shijiagen.utils.R;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户模块控制层
 */
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 检查是否可用该账号注册
     * @param param 接受账号实体类，内部实现参数校验
     * @return
     */
    @PostMapping("check")
    public R check(@RequestBody @Validated UserCheckParam param){
        Long total = userService.check(param);
        if (total == 0){
            return R.ok("账号不存在可以使用!");
        }
        return R.fail("账号已经存在!");
    }

    /**
     * 用户账号注册
     * @param user
     * @return
     */
    @PostMapping("register")
    public R register(@RequestBody @Validated User user){
        return userService.register(user) ? R.ok("注册成功!") : R.fail("注册失败!请稍后重试或者联系网站管理员");
    }

    /**
     * 用户登陆
     * @param loginParam
     * @return
     */
    @PostMapping("login")
    public R login(@RequestBody @Validated UserLoginParam loginParam){
        User user = userService.login(loginParam);
        if(user != null){
            user.setPassword(null);
            return R.ok("登陆成功",user);
        }else {
            return R.fail("账号或密码不存在!");
        }
    }
}
